package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.BlowDeviceDto;
import com.jdone.compus.dto.BlowDeviceQuery;
import com.jdone.compus.model.BlowDevice;
import com.jdone.compus.service.BlowDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/blow/devices")
@Api(value = "吹风机设备管理", tags = "吹风机设备管理")
public class BlowDeviceController {

    @Autowired
    private BlowDeviceService blowDeviceService;

    @ApiOperation("新增设备")
    @PostMapping("/end_back/add")
    public ApiResponse addDevice(
            @Valid @RequestBody BlowDeviceDto dto
    ) {
        try {
            BlowDevice saved = blowDeviceService.saveFromDto(dto);
            return ApiResponse.success(saved);
        } catch (Exception ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("修改设备")
    @PutMapping("/end_back/update")
    public ApiResponse updateDevice(
            @Valid @RequestBody BlowDeviceDto dto
    ) {
        try {
            BlowDevice updated = blowDeviceService.updateFromDto(dto.getId(), dto);
            return ApiResponse.success(updated);
        } catch (EntityNotFoundException ex) {
            return ApiResponse.error("设备不存在，ID=" + dto.getId());
        } catch (Exception ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("根据设备 ID 获取设备信息")
    @GetMapping("/wechat/findById")
    public ApiResponse getDeviceById(@RequestParam Long deviceId) {
        try {
            BlowDevice device = blowDeviceService.getDeviceById(deviceId);
            return ApiResponse.success(device);
        } catch (Exception ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("分页查询设备列表")
    @GetMapping("/end_back/findAll")
    public ApiResponse listDevices(
            @ModelAttribute BlowDeviceQuery query,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createdAt").descending());
        Page<BlowDevice> result = blowDeviceService.pageQuery(query, pageable);
        return ApiResponse.success(result);
    }

    @ApiOperation("逻辑删除吹风机设备")
    @DeleteMapping("/blowDevices/{id}")
    public ApiResponse deleteBlowDevice(@PathVariable Long id) {
        blowDeviceService.logicalDelete(id);
        return new ApiResponse(200, true, "删除成功", null);
    }

    @ApiOperation("8/10批量设置设备的使用时间段。deviceIds 为逗号分隔的 id 列表，useTime 为要写入的文本")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceIds", value = "设备 id 列表，逗号分隔，例如: 1,2,3", required = true, dataType = "string", paramType = "query", example = "1,2,3"),
            @ApiImplicitParam(name = "useTime", value = "使用时间段文本，例如: 08:00-12:00|15:00-19:00", required = true, dataType = "string", paramType = "query", example = "08:00-12:00|15:00-19:00")
    })
    @PostMapping("/bulk-use-time")
    public ApiResponse bulkUpdateUseTime(
            @RequestParam("deviceIds") String deviceIds,
            @RequestParam("useTime") String useTime
    ) {
        try {
            int updated = blowDeviceService.bulkUpdateUseTime(deviceIds, useTime);
            Map<String, Object> data = new HashMap<>();
            data.put("updatedCount", updated);
            data.put("deviceIds", deviceIds);
            data.put("useTime", useTime);
            return new ApiResponse(0, true, "批量更新成功", data);
        } catch (IllegalArgumentException ex) {
            return new ApiResponse(400, false, ex.getMessage(), null);
        } catch (Exception ex) {
            // 打印日志会更好：logger.error("批量更新 useTime 出错", ex);
            return new ApiResponse(500, false, "服务异常，批量更新失败", null);
        }
    }
}
